<template>
  <el-main>
    <!-- 查询条件 -->
    <el-form :model="searchModel" ref="searchForm" label-width="80px" :inline="true" size="small">
      <el-form-item>
        <el-input v-model="searchModel.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="search" icon="el-icon-search">查询</el-button>
        <el-button icon="el-icon-refresh-right" plain type="info" @click="reset">重置</el-button>
        <el-button type="success" plain icon="el-icon-plus" @click="openAddWindow">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格 -->
    <el-table :data="roleList" v-loading="loading" :height="tableHeight" border stripe
      style="width: 100%; margin-bottom: 10px">
      <el-table-column prop="id" label="角色编号" align="center"></el-table-column>
      <el-table-column prop="roleCode" align="center" label="角色编码"></el-table-column>
      <el-table-column prop="roleName" align="center" label="角色名称"></el-table-column>
      <el-table-column prop="remark" align="center" label="角色备注"></el-table-column>
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <!-- <span style="color: #1890FF;cursor: pointer;" @click="handleEdit(scope.row)">编辑 </span> -->
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleEdit(scope.row)">编辑
          </el-button>
          <!-- <span style="color: #40BA86;cursor: pointer;" @click="handleDelete(scope.row)">删除 </span>
          <span style="color: #A692FF;cursor: pointer;" @click="assignRole(scope.row)">分配权限 </span> -->

          <el-button icon="el-icon-delete" type="danger" size="mini" @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button icon="el-icon-setting" type="primary" size="mini" @click="assignRole(scope.row)">分配权限
          </el-button>
        </template></el-table-column></el-table>

    <!-- 分页工具栏 -->
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo" :page-sizes="[10, 20, 30, 40, 50]" :page-size="10"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <system-dialog :title="roleDialog.title" :width="roleDialog.width" :height="roleDialog.height"
      :visible="roleDialog.visible" @onClose="onClose" @onConfirm="onConfirm">
      <div slot="content">
        <el-form :model="role" ref="roleForm" :rules="rules" label-width="80px" :inline="false" size="small">
          <el-form-item prop="roleCode" label="角色编码">
            <el-input v-model="role.roleCode" placeholder="请输入角色编码"></el-input>
          </el-form-item>
          <el-form-item prop="roleName" label="角色名称">
            <el-input v-model="role.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input type="textarea" v-model="role.remark"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </system-dialog>

    <!-- 分配角色对话框 -->
    <!-- 分配权限树窗口 -->
    <system-dialog :title="assignDialog.title" :visible="assignDialog.visible" :width="assignDialog.width"
      :height="assignDialog.height" @onClose="onAssignClose" @onConfirm="onAssignConfirm">
      <div slot="content">
        <el-tree ref="assignTree" :data="assignTreeData" node-key="id" :props="defaultProps" empty-text="暂无数据"
          :show-checkbox="true" :highlight-current="true" default-expand-all></el-tree>
      </div>
    </system-dialog>
  </el-main>
</template>


<script>
  import {
    getRoles,
    addRole,
    updateRole,
    deleteRole,
    checkRoleApi,
    getAssignTreeApi,
    assignSaveApi,
  } from "@/api/role";
  import SystemDialog from "@/components/system/SystemDialog";
  import leafUtils from "@/utils/leaf";
  export default {
    name: "roleList",

    components: {
      SystemDialog,
    },

    data() {
      return {
        loading: false,
        //分配权限窗口属性
        assignDialog: {
          title: "",
          visible: false,
          height: 450,
          width: 300,
        },
        roleId: "", //角色ID
        assignTreeData: [], //树节点数据
        //树节点属性
        defaultProps: {
          children: "children",
          label: "label",
        },
        rules: {
          roleCode: [
            { required: true, trigger: "blur", message: "请输入角色编码" },
          ],
          roleName: [
            { required: true, trigger: "blur", message: "请输入角色名称" },
          ],
        },
        roleDialog: {
          title: "新增角色",
          visible: false,
          width: 500,
          height: 230,
        },
        role: {
          roleCode: "",
          roleName: "",
          remark: "",
          id: "",
        },
        searchModel: {
          roleName: "",
          pageNo: 1,
          pageSize: 10,
        },
        tableHeight: 0,

        roleList: [],
        total: 10,
      };
    },

    created() {
      this.search();
    },

    mounted() {
      this.$nextTick(() => {
        this.tableHeight = window.innerHeight - 180;
      });
    },

    methods: {
      setLeaf(arr) {
        if (arr && arr.length > 0) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].children && arr[i].children.length > 0) {
              arr[i].open = false;
              this.setLeaf(arr[i].children);
            } else {
              arr[i].open = true;
            }
          }
        }
        return arr;
      },

      /**
       * 确认按钮
       */
      async onAssignConfirm() {
        let ids = this.$refs.assignTree.getCheckedKeys();
        let pids = this.$refs.assignTree.getHalfCheckedKeys();
        let listId = ids.concat(pids);
        let params = {
          roleId: this.roleId,
          list: listId,
        };
        let res = await assignSaveApi(params);
        if (res.success) {
          this.assignDialog.visible = false;
          this.$message.success(res.message);
        } else {
          this.$message.success(res.message);

        }
      },
      onAssignClose() {
        this.assignDialog.visible = false;
      },
      openAddWindow() {
        this.$resetForm("roleForm", this.role);
        this.roleDialog.visible = true;
        this.roleDialog.title = "新增角色";
      },
      onConfirm() {
        this.$refs.roleForm.validate(async (valid) => {
          if (valid) {
            let res = null;
            if (this.role.id != "") {
              // 修改操作
              res = await updateRole(this.role);
            } else {
              // 新增
              res = await addRole(this.role);
            }

            if (res.success) {
              this.$message.success(res.message);
              this.search();
              this.roleDialog.visible = false;
            } else {
              // this.$
              this.$message.error(res.message);
            }
          }
          //   if(valid){
          //     let res =  null
          //     if(this.role.id !=''){ // 修改操作

          // this.roleDialog.visible = false;
          //         // res =await  updateRole
          //   }else{

          //   }
        });
      },
      onClose() {
        this.roleDialog.visible = false;
      },
      reset() {
        this.searchModel.roleName = "";
        this.search();
      },
      async search() {
        try {
          this.loading = true
          let res = await getRoles(this.searchModel);
          if (res.success) {
            this.roleList = res.data.records;
            this.total = res.data.total;
          }
        } catch (e) {
          console.log(e)
        } finally {
          this.loading = false
        }

      },
      handleSizeChange(size) {
        this.searchModel.pageSize = size;
        this.search();
      },
      handleCurrentChange(page) {
        this.searchModel.pageNo = page;
        this.search();
      },
      handleEdit(row) {
        // 数据回显
        this.$objCopy(row, this.role);
        this.roleDialog.visible = true;
        this.roleDialog.title = "编辑角色";
      },
      async handleDelete(row) {
        let result = await checkRoleApi({ id: row.id });
        if (!result.success) {
          //  说明该角色已被分配
          this.$message.warning(result.message);
        } else {
          // 删除
          let confirm = await this.$myconfirm("确定删除该数据");
          if (confirm) {
            let res = await deleteRole({ id: row.id });
            if (res.success) {
              this.$message.success("删除成功");
              this.roleDialog.visible = false;
              this.searchModel.pageNo = 1;
              this.searchModel.pageSize = 10;
              this.search();
            } else {
              this.$message.error("删除失败");
            }
          } else {
            // 取消按钮
          }
        }
      },
      async assignRole(row) {
        this.roleId = row.id;
        let params = {
          roleId: row.id,
          // userId:
        };
        let res = await getAssignTreeApi(params);
        console.log(res);
        if (res.success) {
          // 当前用户拥有的菜单权限
          let { permissionList } = res.data;
          // 获取当前被分配角色功能已拥有的菜单权限
          let { checkList } = res.data;
          // 判断当前菜单是否是最后一级
          // let { setLeaf } = leafUtils;
          // 设置权限菜单列表
          let newPermissionList = this.setLeaf(permissionList);
          //  设置树节点数据
          this.assignTreeData = newPermissionList;
          this.$nextTick(() => {
            // 获取菜单节点数据
            let nodes = this.$refs.assignTree.children;
            // 设置子节点
            this.setChild(nodes, checkList);
          });
        }
        this.assignDialog.title = `给${row.roleName}分配权限`;

        this.assignDialog.visible = true;
      },
      // 设置子节点
      setChild(childNodes, checkList) {
        // 判断是否存在子节点
        if (childNodes && childNodes.length > 0) {
          // 循环所有的权限
          for (let i = 0; i < childNodes.length; i++) {
            // 根据data获取组件中的node节点
            let node = this.$refs.assignTree.getNode(childNodes[i]);
            if (checkList && checkList.length > 0) {
              // 遍历已有的权限集合
              for (let j = 0; j < checkList.length; j++) {
                // 判断权限id是否相等
                if (childNodes[i].id === checkList[j]) {
                  // 判断节点的状态，如果当前节点是展开的，则将树节点选中
                  if (childNodes[i].open) {
                    this.$refs.assignTree.setChecked(node, true);
                    break;
                  }
                }
              }
            }
            // 判断存在子节点，则递归选中
            this.setChild(childNodes[i].children, checkList);
          }
        }
      },
    },
  };
</script>

<style scoped>
  /deep/ .has-gutter th {
    background-color: #F2F6FC;
  }
</style>